<template>
  <div class="page-bg">
    <div class="main-container">
      <div class="sidebar">
        <div class="sidebar-header">
          <div class="header-content">
            <router-link to="/" class="logo-link">
              <div class="logo">
                <i class="fas fa-plane"></i>
                <div>TripMateAI</div>
              </div>
            </router-link>
            <!-- <div class="search-box">
              <i class="fas fa-search"></i>
              <input type="text" placeholder="搜索对话..." />
            </div> -->
          </div>
          <button class="new-chat-btn" @click="startNewChat">
            <i class="fas fa-plus"></i> 开启新对话
          </button>
        </div>

        <div class="history-section">
          <!-- 历史记录标题和统计信息 -->
          <div v-if="isLoggedIn" class="section-header">
            <span>历史记录</span>
            <span>{{ chatHistory.length }} 个对话</span>
          </div>
          
          <!-- 未登录提示和登录按钮 -->
          <div v-if="!isLoggedIn" class="login-prompt">
            <div class="prompt-content">
              <i class="fas fa-user-lock"></i>
              <h3>登录后可保存对话记录</h3>
              <p>登录账户即可保存和查看历史对话记录</p>
              <button class="login-btn" @click="showAuthModal = true">
                立即登录
              </button>
            </div>
          </div>
          
          <!-- 历史记录列表 -->
          <div 
            v-if="isLoggedIn"
            ref="historyListContainer"
            class="history-list" 
            @scroll="handleHistoryScroll"
          >
            <div
              v-for="(history, index) in chatHistory"
              :key="history.id"
              :class="['history-item', { active: activeChatId === history.id }]"
              @click="loadChatHistory(history.id)"
            >
              <i class="fas fa-comment"></i>
              <div class="history-content">
                <div class="history-title">{{ history.title || '新对话' }}</div>
                <div class="history-preview">{{ history.preview || '点击继续对话' }}</div>
              </div>
              <div class="history-time">{{ formatDate(history.timestamp) }}</div>
            </div>
            <!-- 加载更多指示器 -->
            <div v-if="isLoadingHistory" class="loading-more">
              <i class="fas fa-spinner fa-spin"></i> 加载中...
            </div>
            <div v-else-if="!hasMoreHistory && chatHistory.length > 0" class="no-more-data">
              没有更多记录了
            </div>
          </div>
        </div>

        <div class="sidebar-footer">
          <div class="user-info">
            <div class="user-avatar">
              <i class="fas fa-user"></i>
            </div>
            <div class="user-name">{{ loginUser.userName }}</div>
            <div v-if="isLoggedIn" class="logout-btn" @click="handleLogout">
              <i class="fas fa-sign-out-alt"></i>
              <span class="logout-text">退出</span>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-main">
        <div class="chat-container">
          <div class="chat-header">
            <div class="chat-title">
              <i class="fas fa-compass"></i>
              <div>AI旅游助手</div>
            </div>
            <div class="chat-info">您好!我是AI旅游助手,可以为您提供天气查询、车票信息查询、目的地推荐、行程规划等专业建议</div>
          </div>

          <!-- 统一的消息容器 -->
          <div class="chat-messages" ref="messagesContainer">
            <div 
              v-for="msg in messages" 
              :key="msg.timestamp" 
              :class="['message', msg.sender]"
            >
              <div class="avatar">
                <i :class="msg.sender === 'user' ? 'fas fa-user' : 'fas fa-robot'"></i>
              </div>
              <div class="message-content">
                <div class="message-header">
                  <div class="text" v-if="msg.sender === 'ai'" v-html="renderMarkdown(msg.content)"></div>
<div class="text" v-else>{{ msg.content }}</div>
                  <div class="timestamp">{{ formatTime(msg.timestamp) }}</div>
                </div>
              </div>
            </div>

            <div v-if="isLoading" class="message ai">
              <div class="avatar">
                <i class="fas fa-robot"></i>
              </div>
              <div class="message-content">
                <div class="message-header">
                  <div class="text">思考中<span class="dot-flashing"></span></div>
                </div>
              </div>
            </div>
          </div>

          <div class="input-area">
            <div class="input-container">
              <input
                  v-model="inputMessage"
                  placeholder="请输入旅游相关问题，例如：推荐一个适合夏季的中国旅游目的地..."
                  @keyup.enter="sendMessage"
                  :disabled="isLoading"
              />
              <button
                  @click="sendMessage"
                  :class="{ disabled: !inputMessage.trim() || isLoading }"
              >
                <i class="fas fa-paper-plane"></i>
              </button>
            </div>
            <div class="input-hint">TripMateAI可能会犯错误，请核对重要信息</div>
          </div>
        </div>
      </div>
      <AuthModal 
        v-model="showAuthModal" 
        @login-success="handleLoginSuccess"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick, computed, watch } from 'vue';
import { getChatHistory, getChatHistoryByCursor } from '../api/chatController';
import {
  createTripSSEConnection,
  type SSEConnection
} from '../services/sseService';
import AuthModal from '../components/AuthModal.vue';
import { marked } from 'marked';

import { useLoginUserStore } from '../stores/useLoginUserStore'
import { storeToRefs } from 'pinia'

// 对话数据
const messages = ref([
  {
    sender: 'ai',
    content: '您好！我是AI旅游助手，请问您有具体的旅游目的地或行程需求吗？我可以为您提供专业的建议和行程规划。',
    timestamp: new Date().getTime()
  }
]);

// 用户输入
const inputMessage = ref('');

// 加载状态
const isLoading = ref(false);

// 获取 store 实例
const loginUserStore = useLoginUserStore()
const { loginUser, isLoggedIn } = storeToRefs(loginUserStore)
const { fetchLoginUser, setLoginUser, logout } = loginUserStore

// 当前聊天ID生成函数
function getCurrentChatId() {
  const id = loginUser.value && loginUser.value.id ? loginUser.value.id : 'guest';
  return id + '_' + Date.now();
}

// 当前聊天ID
const chatId = ref(getCurrentChatId());
const messagesContainer = ref<HTMLElement | null>(null);
const historyListContainer = ref<HTMLElement | null>(null);

// 当前活跃的聊天ID
const activeChatId = ref(chatId.value);

// 渲染Markdown内容
const renderMarkdown = (content: string) => {
  return marked.parse(content);
};

// SSE 连接引用
let sseConnection: SSEConnection | null = null;

// 显示登录模态框
const showAuthModal = ref(false);

// 历史记录数据
const chatHistory = ref<any[]>([]);
// 游标分页相关状态
const historyCursor = ref<string | null>(null);
const hasMoreHistory = ref(true);
const isLoadingHistory = ref(false);

// 格式化日期
const formatDate = (timestamp: number) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24));

  if (diffDays === 0) return '今天';
  if (diffDays === 1) return '昨天';
  if (diffDays < 7) return `${diffDays}天前`;

  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 使用游标加载历史记录
const loadHistoryWithCursor = async (isInitialLoad = false) => {
  if (!isLoggedIn.value || !loginUser.value?.id || isLoadingHistory.value || (!hasMoreHistory.value && !isInitialLoad)) {
    if (isInitialLoad && chatHistory.value.length === 0) {
      startNewChat()
    }
    return
  }

  isLoadingHistory.value = true
  try {
    const res = await getChatHistoryByCursor({
      userId: loginUser.value.id.toString(),
      pageSize: 10,
      cursor: isInitialLoad ? undefined : historyCursor.value || undefined
    })
    
    console.log('游标查询历史记录结果:', res)
    if (res.data.code === 0 && res.data.data) {
      const { conversations, nextCursor, hasNext } = res.data.data
      
      // 转换数据结构
      const formattedConversations = conversations.map((conversation: any) => ({
        id: conversation.conversationId,
        title: conversation.messages[0]?.content?.substring(0, 20) || '未命名对话',
        preview: conversation.messages[0]?.content || '',
        timestamp: conversation.messages.length > 0 ? new Date(conversation.messages[0].timestamp).getTime() : new Date().getTime(),
        messages: conversation.messages.map((msg: any) => ({
          sender: msg.type === 'USER' ? 'user' : 'ai',
          content: msg.content,
          timestamp: new Date(msg.timestamp).getTime()
        }))
      }))

      if (isInitialLoad) {
        chatHistory.value = formattedConversations.sort((a, b) => b.timestamp - a.timestamp)
        console.log('初始加载历史记录完成，共', chatHistory.value.length, '条')
        if (chatHistory.value.length > 0) {
          loadChatHistory(chatHistory.value[0].id)
        } else {
          startNewChat()
        }
      } else {
        // 追加到现有历史记录，并重新排序
        chatHistory.value.push(...formattedConversations)
        chatHistory.value.sort((a, b) => b.timestamp - a.timestamp)
      }

      historyCursor.value = nextCursor || null
      hasMoreHistory.value = hasNext || false
    } else {
      console.log('没有历史记录数据')
      if (isInitialLoad) {
        startNewChat()
      }
    }
  } catch (error) {
    console.error('获取历史对话失败:', error)
    if (isInitialLoad) {
      startNewChat()
    }
  } finally {
    isLoadingHistory.value = false
  }
};

// 防抖函数
const debounce = (func: Function, wait: number) => {
  let timeout: number | null;
  return function (...args: any[]) {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait) as any;
  };
};

// 处理历史记录区域滚动事件（防抖版本）
const handleHistoryScroll = debounce((event: Event) => {
  const target = event.target as HTMLElement;
  const { scrollTop, scrollHeight, clientHeight } = target;
  
  // 当滚动到底部时加载更多
  if (scrollHeight - scrollTop - clientHeight <= 100 && hasMoreHistory.value && !isLoadingHistory.value) {
    loadHistoryWithCursor();
  }
}, 200);

// 开启新对话
const startNewChat = () => {
  chatId.value = getCurrentChatId();
  activeChatId.value = chatId.value;

  // 重置消息
  messages.value = [
    {
      sender: 'ai',
      content: '您好！我是AI旅游助手，请问您有具体的旅游目的地或行程需求吗？我可以为您提供专业的建议和行程规划。',
      timestamp: new Date().getTime()
    }
  ];

  // 添加到历史记录（仅限登录用户）
  if (isLoggedIn.value && loginUser.value?.id) {
    chatHistory.value.unshift({
      id: chatId.value,
      title: '新对话',
      preview: '',
      timestamp: new Date().getTime()
    });
  }
  scrollToBottom();
};

// 加载历史对话
const loadChatHistory = async (id: string) => {
  console.log('加载历史对话，ID:', id);
  
  // 设置当前聊天ID
  chatId.value = id;
  activeChatId.value = id;
  
  try {
    // 向后端请求获取该对话的完整历史记录
    const res = await getChatHistory({
      userId: loginUser.value?.id?.toString() || ''
    });
    
    console.log('获取对话历史结果:', res);
    
    if (res.data.code === 0 && res.data.data) {
      // 查找对应的对话
      const targetConversation = res.data.data.find((conv: any) => conv.conversationId === id);
      
      if (targetConversation && targetConversation.messages && targetConversation.messages.length > 0) {
        // 转换消息格式
        messages.value = targetConversation.messages.map((msg: any) => ({
          sender: msg.type === 'USER' ? 'user' : 'ai',
          content: msg.content,
          timestamp: new Date(msg.timestamp).getTime()
        }));
        
        console.log('成功加载对话消息，共', messages.value.length, '条');
      } else {
        // 没有找到对话或对话为空，显示欢迎语
        console.log('未找到对话或对话为空，显示欢迎语');
        messages.value = [
          {
            sender: 'ai',
            content: '您好！我是AI旅游助手，请问您有具体的旅游目的地或行程需求吗？我可以为您提供专业的建议和行程规划。',
            timestamp: new Date().getTime()
          }
        ];
      }
    } else {
      // API调用失败，显示欢迎语
      console.log('API调用失败，显示欢迎语');
      messages.value = [
        {
          sender: 'ai',
          content: '您好！我是AI旅游助手，请问您有具体的旅游目的地或行程需求吗？我可以为您提供专业的建议和行程规划。',
          timestamp: new Date().getTime()
        }
      ];
    }
  } catch (error) {
    console.error('获取对话历史失败:', error);
    // 请求失败，显示欢迎语
    messages.value = [
      {
        sender: 'ai',
        content: '您好！我是AI旅游助手，请问您有具体的旅游目的地或行程需求吗？我可以为您提供专业的建议和行程规划。',
        timestamp: new Date().getTime()
      }
    ];
  }
  
  scrollToBottom();
};

// 处理登录成功事件
const handleLoginSuccess = async (userData: any) => {
  console.log('登录成功，用户数据:', userData)
  setLoginUser(userData)
  // 获取完整用户信息
  const fetchSuccess = await fetchLoginUser()
  console.log('获取用户信息结果:', fetchSuccess, '用户信息:', loginUser.value)
  chatId.value = getCurrentChatId();
  
  // 加载历史记录
  if (fetchSuccess && loginUser.value && loginUser.value.id) {
    await loadHistoryWithCursor(true)
  } else {
    startNewChat()
  }
}

// 处理登出
const handleLogout = () => {
  logout()
  chatHistory.value = []
  startNewChat()
}

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || isLoading.value) return;

  // 添加用户消息
  messages.value.push({
    sender: 'user',
    content: message,
    timestamp: new Date().getTime()
  });
  scrollToBottom();

  // 清空输入框
  inputMessage.value = '';
  isLoading.value = true;

  try {
    // 关闭现有连接（如果有）
    if (sseConnection) {
      sseConnection.close();
      sseConnection = null;
    }

    // 初始化AI消息
    let aiResponse = {
      sender: 'ai',
      content: '',
      timestamp: new Date().getTime()
    };
    messages.value.push(aiResponse);

    scrollToBottom();

    // 更新当前对话的标题（如果是新对话）- 修复：使用函数检查登录状态
    if (messages.value.filter(m => m.sender === 'user').length === 1 && isLoggedIn.value) {
      const currentHistory = chatHistory.value.find(h => h.id === chatId.value);
      if (currentHistory && currentHistory.title === '新对话') {
        currentHistory.title = message.substring(0, 20) + (message.length > 20 ? '...' : '');
      }
    }

    // 创建新的 SSE 连接
    sseConnection = createTripSSEConnection(
      { 
        message, 
        chatId: chatId.value,
        userId: isLoggedIn.value && loginUser.value?.id ? loginUser.value.id.toString() : undefined
      },
      // 消息接收回调
      (dataChunk) => {
        // 追加内容到最新AI消息
        const lastIndex = messages.value.length - 1;
        if (messages.value[lastIndex].sender === 'ai') {
          messages.value[lastIndex].content += dataChunk;
          
          // 自动滚动到底部
          nextTick(() => {
            if (messagesContainer.value) {
              messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
            }
          });
        }
      },
      // 错误处理回调
      (error) => {
        console.error('SSE 连接错误:', error);
        messages.value.push({
          sender: 'ai',
          content: '连接出错，请重试',
          timestamp: new Date().getTime()
        });
        scrollToBottom();
      },
      // 完成回调
      () => {
        isLoading.value = false;
        sseConnection = null;

        // 更新对话预览（仅限登录用户）
        if (isLoggedIn.value) {
          const lastUserMsg = [...messages.value].reverse().find(m => m.sender === 'user');
          if (lastUserMsg) {
            const currentHistory = chatHistory.value.find(h => h.id === chatId.value);
            if (currentHistory) {
              currentHistory.preview = lastUserMsg.content.substring(0, 30) +
                  (lastUserMsg.content.length > 30 ? '...' : '');
              currentHistory.timestamp = new Date().getTime();
            }
          }
        }
        scrollToBottom();
      }
    );

  } catch (error) {
    console.error('请求初始化失败:', error);
    messages.value.push({
      sender: 'ai',
      content: '请求失败，请重试',
      timestamp: new Date().getTime()
    });
    scrollToBottom();
    isLoading.value = false;
  }
};

// 滚动到底部的方法
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 组件卸载时关闭连接
onBeforeUnmount(() => {
  if (sseConnection) {
    sseConnection.close();
  }
});

// 监听登录状态变化
watch(isLoggedIn, (newIsLoggedIn) => {
  console.log('登录状态变化:', newIsLoggedIn)
  if (newIsLoggedIn) {
    // 登录状态变为已登录，加载历史记录
    loadHistoryWithCursor(true)
  } else {
    // 登录状态变为未登录，清空历史记录
    chatHistory.value = []
    startNewChat()
  }
})

// 组件挂载时初始化
onMounted(async () => {
  console.log('TripChat组件挂载，当前登录状态:', isLoggedIn.value)
  
  // 如果localStorage中有用户信息但状态为未登录，尝试恢复登录状态
  if (!isLoggedIn.value) {
    const storedUser = localStorage.getItem('loginUser')
    if (storedUser) {
      try {
        const userData = JSON.parse(storedUser)
        if (userData.id && userData.userName !== '未登录') {
          console.log('从localStorage恢复用户信息:', userData)
          setLoginUser(userData)
          // 验证登录状态是否有效
          const isValid = await fetchLoginUser()
          if (isValid) {
            console.log('登录状态验证成功，加载历史记录')
            await loadHistoryWithCursor(true)
          } else {
            console.log('登录状态验证失败，清空用户状态')
            logout()
          }
        }
      } catch (error) {
        console.error('恢复用户信息失败:', error)
        localStorage.removeItem('loginUser')
      }
    }
  } else {
    // 已登录状态，直接加载历史记录
    console.log('用户已登录，加载历史记录')
    await loadHistoryWithCursor(true)
  }
}) 

</script>

<style scoped>
/* 页面背景 */
.page-bg {
  min-height: 100vh;
  background: #ffffff;
  display: flex;
  align-items: stretch;
  justify-content: flex-start;
  padding: 0;
  margin: 0;
  width: 100vw;
  max-width: 100vw;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.main-container {
  display: flex;
  flex: 1;
  width: 100%;
  max-width: 100vw;
  height: 100vh;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  align-items: stretch;
  justify-content: flex-start;
  transition: all 0.3s ease;
  border-top: 1px solid #e5e7eb;
}

@media (max-width: 768px) {
  .main-container {
    gap: 16px;
    padding: 10px;
  }

  .sidebar {
    width: 100%;
    max-width: 320px;
    min-height: auto;
    max-height: 85vh;
    border-radius: 20px;
  }

  .chat-container {
    width: 100%;
    max-width: none;
    height: 85vh;
    border-radius: 20px;
  }

  .chat-header {
    padding: 24px 28px 16px;
  }

  .chat-title {
    font-size: 20px;
  }

  .message .avatar {
    width: 36px;
    height: 36px;
    font-size: 18px;
    margin: 0 8px;
  }

  .text {
  padding: 14px 20px;
  font-size: 14px;
  border-radius: 16px 16px 4px 16px;
}

/* Markdown样式 */
:deep(.text h1) {
  font-size: 24px;
  font-weight: bold;
  margin: 16px 0;
}
:deep(.text h2) {
  font-size: 20px;
  font-weight: bold;
  margin: 14px 0;
}
:deep(.text h3) {
  font-size: 18px;
  font-weight: bold;
  margin: 12px 0;
}
:deep(.text ul),
:deep(.text ol) {
  margin: 10px 0;
  padding-left: 24px;
}
:deep(.text ul) {
  list-style-type: disc;
}
:deep(.text ol) {
  list-style-type: decimal;
}
:deep(.text p) {
  margin: 8px 0;
}
:deep(.text strong) {
  font-weight: bold;
}
:deep(.text em) {
  font-style: italic;
}
:deep(.text a) {
  color: #667eea;
  text-decoration: underline;
}
:deep(.text pre) {
  background-color: #f3f4f6;
  padding: 12px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 10px 0;
}
:deep(.text code) {
  background-color: #f3f4f6;
  padding: 2px 4px;
  border-radius: 4px;
  font-family: monospace;
}
:deep(.text blockquote) {
  border-left: 4px solid #667eea;
  padding-left: 12px;
  margin: 10px 0;
  color: #6b7280;
}

  .input-container {
    padding: 12px 16px;
    gap: 12px;
  }

  button {
    width: 48px;
    height: 48px;
    font-size: 20px;
  }
}

.sidebar {
  width: 260px;
  min-width: 260px;
  background: #f9fafb;
  color: #374151;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px);
  overflow: hidden;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #ffffff;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  padding: 8px 12px;
  transition: all 0.2s ease;
}

.search-box:focus-within {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.search-box i {
  color: #6b7280;
  font-size: 14px;
}

.search-box input {
  background: transparent;
  border: none;
  color: #374151;
  outline: none;
  flex: 1;
  font-size: 14px;
}

.search-box input::placeholder {
  color: #9ca3af;
}

.logo-link {
  text-decoration: none;
  color: inherit;
}

.logo {
  display: flex;
  align-items: center;
  gap: 14px;
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 28px;
}

.logo i {
  background: rgba(255, 255, 255, 0.15);
  width: 48px;
  height: 48px;
  border-radius: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
}

.new-chat-btn {
  width: 100%;
  padding: 10px 16px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.new-chat-btn:hover {
  background: #5a67d8;
}

.history-section {
  flex: 1;
  padding: 20px 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
  max-height: calc(100vh - 200px);
}

.section-header {
  display: flex;
  justify-content: space-between;
  padding: 0 28px 20px;
  font-size: 14px;
  opacity: 0.8;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  margin: 0 20px;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px 20px;
  min-height: 100px;
  max-height: calc(100vh - 250px);
}

.history-item {
  padding: 12px 16px;
  margin: 8px 0;
  border-radius: 8px;
  background: #ffffff;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: flex-start;
  gap: 14px;
  border-left: 2px solid transparent;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.history-item.active {
  border-left-color: #667eea;
  background: #f3f4f6;
  color: #667eea;
}

.history-item:hover {
  background: #f3f4f6;
  color: #374151;
}

.history-item i {
  margin-top: 3px;
  font-size: 16px;
  opacity: 0.8;
}

.history-content {
  flex: 1;
  min-width: 0;
}

.history-title {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-preview {
  font-size: 14px;
  opacity: 0.8;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.history-time {
  font-size: 12px;
  opacity: 0.7;
  white-space: nowrap;
  padding-top: 4px;
}

.loading-more,
.no-more-data {
  text-align: center;
  padding: 20px;
  font-size: 14px;
  opacity: 0.7;
  color: rgba(255, 255, 255, 0.6);
}

.loading-more i {
  margin-right: 8px;
}

/* 未登录提示样式 */
.login-prompt {
  padding: 20px 28px;
  text-align: center;
  color: #374151;
}

.login-prompt .prompt-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.login-prompt i {
  font-size: 56px;
  background: #f3f4f6;
  color: #667eea;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-prompt h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #111827;
}

.login-prompt p {
  margin: 0;
  font-size: 15px;
  color: #6b7280;
  line-height: 1.5;
}

.login-btn {
  margin-top: 16px;
  padding: 12px 24px;
  background: #667eea;
  height : 40px;
  width: 120px;
  color: white;
  border: none;
  border-radius: 24px;
  font-size: 17px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.login-btn:hover {
  background: #5a67d8;
  transform: translateY(-2px);
}

.logout-btn {
  margin-left: 10px;
  cursor: pointer;
  color: #ff6b6b;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 5px 10px;
  border-radius: 8px;
}

.logout-btn:hover {
  background: rgba(255, 107, 107, 0.1);
  color: #ff4b4b;
}

.logout-text {
  font-size: 14px;
  font-weight: 500;
}

.sidebar-footer {
  padding: 24px 28px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #4a6cf7;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  color: white;
}

.user-name {
  flex-grow: 1;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-main {
  flex: 1;
  width: 100%;
  max-width: none;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 0;
  margin: 0;
}

.chat-container {
  flex: 1;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: calc(100vh - 48px);
  transition: all 0.3s ease;
}

.chat-header {
  padding: 12px 16px;
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  box-shadow: none;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #111827;
}

.chat-title i {
  color: #667eea;
  font-size: 18px;
}

.chat-info {
  margin-top: 4px;
  font-size: 14px;
  color: #6b7280;
  line-height: 1.4;
}
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px 24px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  background: #ffffff;
  width: 100%;
  max-width: none;
}

.message {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  animation: fadeInUp 0.3s ease-out;
}

/* 骨架屏样式 */
.skeleton-item {
  padding: 12px 16px;
  margin: 8px 0;
  border-radius: 16px;
  background: linear-gradient(to right, #4a5568 8%, #2d3748 18%, #4a5568 33%);
  background-size: 1000px 100%;
  animation: shimmer 1.5s infinite linear;
  height: 60px;
}

.skeleton-avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background: #4a5568;
  animation: pulse 1.5s infinite;
}

.skeleton-content {
  flex: 1;
  height: 40px;
  background: #4a5568;
  border-radius: 12px;
  animation: pulse 1.5s infinite;
  margin-left: 12px;
}

/* 合并用户消息样式定义，解决冲突 */
.message.user {
  flex-direction: row-reverse !important;
  align-self: flex-end !important;
  margin-left: auto !important;
  max-width: 70%;
  width: fit-content;
  justify-content: flex-end;
  color: white;
  border-radius: 18px 18px 4px 18px;
}

.message.user .message-content {
  border-radius: 18px 18px 4px 18px;
}



.message .avatar {
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #e5e7eb;
  color: #6b7280;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  align-self: flex-start;
}

.message.user .avatar {
  background: #667eea;
  color: white;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.message.user .message-content {
  align-items: flex-end;
}

.message-header {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  flex-direction: column;
}

.text {
  padding: 12px 35px;
  border-radius: 12px;
  line-height: 1.5;
  font-size: 14px;
  background: #f3f4f6;
  color: #374151;
  word-break: break-word;
}

.message.user .text {
  background: #667eea;
  color: white;
  border-radius: 12px;
}

.timestamp {
  font-size: 12px;
  color: #888;
  align-self: flex-end;
  margin-top: 6px;
  padding: 2px 8px;
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.03);
}

.message.user .timestamp {
  align-self: flex-end;
  color: rgba(255, 255, 255, 0.7);
  background: rgba(255, 255, 255, 0.1);
}

.message.ai .timestamp {
  align-self: flex-end;
}

.input-area {
  width: 100%;
  background: #ffffff;
  border-top: 1px solid #e5e7eb;
  padding: 8px 24px 60px 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.input-container {
  display: flex;
  gap: 8px;
  width: 100%;
  max-width: 800px;
  background: #ffffff;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  padding: 8px 12px;
  transition: all 0.2s ease;
}

.input-container:focus-within {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

input {
  flex: 1;
  padding: 8px 12px;
  border: none;
  font-size: 14px;
  outline: none;
  background: transparent;
}

input::placeholder {
  color: #9ca3af;
}

button {
  width: 32px;
  height: 32px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

button:hover:not(.disabled) {
  background: #5a67d8;
}

button:hover:not(.disabled) {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(118, 75, 162, 0.15);
}

button.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.input-hint {
  text-align: center;
  font-size: 13px;
  color: #999;
  margin-top: 12px;
}

/* 加载动画样式 */
.dot-flashing {
  position: relative;
  display: inline-block;
  width: 10px;
  height: 10px;
  margin-left: 6px;
  border-radius: 5px;
  background-color: #999;
  color: #999;
  animation: dotFlashing 1s infinite linear alternate;
  animation-delay: .5s;
}

.dot-flashing::before, .dot-flashing::after {
  content: '';
  display: inline-block;
  position: absolute;
  top: 0;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #999;
  color: #999;
}

.dot-flashing::before {
  left: -15px;
  animation: dotFlashing 1s infinite alternate;
  animation-delay: 0s;
}

.dot-flashing::after {
  left: 15px;
  animation: dotFlashing 1s infinite alternate;
  animation-delay: 1s;
}

@keyframes dotFlashing {
  0% { background-color: #999; }
  50%, 100% { background-color: #e6e6e6; }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0%, 100% { opacity: 0.6; }
  50% { opacity: 0.3; }
}

@keyframes shimmer {
  0% { background-position: -1000px 0; }
  100% { background-position: 1000px 0; }
}

/* 滚动条样式 */
.sidebar ::-webkit-scrollbar, .messages-container ::-webkit-scrollbar, .history-list ::-webkit-scrollbar {
  width: 6px;
}

.sidebar ::-webkit-scrollbar-track, .messages-container ::-webkit-scrollbar-track, .history-list ::-webkit-scrollbar-track {
  background: transparent;
}

.history-list ::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 10px;
}

.history-list ::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

.messages-container ::-webkit-scrollbar-thumb {
  background: rgba(102, 126, 234, 0.2);
  border-radius: 10px;
}

.messages-container ::-webkit-scrollbar-thumb:hover {
  background: rgba(102, 126, 234, 0.3);
}

.sidebar ::-webkit-scrollbar-track,
.messages-container ::-webkit-scrollbar-track,
.history-list ::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
}

.sidebar ::-webkit-scrollbar-thumb,
.messages-container ::-webkit-scrollbar-thumb,
.history-list ::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 10px;
}

.sidebar ::-webkit-scrollbar-thumb:hover,
.messages-container ::-webkit-scrollbar-thumb:hover,
.history-list ::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .page-bg {
    padding: 40px 20px;
  }
  
  .main-container {
    gap: 32px;
    max-width: 1200px;
  }
  
  .sidebar {
    width: 320px;
  }
  
  .chat-container {
    width: 680px;
  }
}

@media (max-width: 768px) {
  .page-bg {
    padding: 20px 10px;
  }
  
  .main-container {
    flex-direction: column;
    gap: 24px;
    align-items: center;
  }
  
  .sidebar {
    width: 100%;
    max-width: 400px;
    min-height: 400px;
  }
  
  .chat-main {
    width: 100%;
    max-width: 100%;
  }
  
  .chat-container {
    width: 100%;
    border-radius: 20px;
  }
  
  .chat-header {
    padding: 24px 20px 16px 20px;
  }
  
  .chat-messages {
    padding: 24px 20px 24px 20px;
    gap: 24px;
  }
  
  .input-area {
    padding: 20px 20px 0 20px;
    margin-top: 24px;
  }
}
</style>